package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepPlan;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepPlanDetail;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepPlanTarget;
import com.mxpio.erp.common.equipment.service.EquipmentUpkeepPlanService;
import com.mxpio.erp.common.equipment.service.EquipmentUpkeepPlanTargetService;
import com.mxpioframework.common.util.SpringUtil;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.system.service.SnRuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Tag(name = "EquipmentUpkeepPlanController}", description = "保养计划")
@RestController
@RequestMapping("/erp/equipment/upkeep/plan/")
public class EquipmentUpkeepPlanController {

    @Autowired
    private EquipmentUpkeepPlanService equipmentUpkeepPlanService;
    @Autowired
    private EquipmentUpkeepPlanTargetService equipmentUpkeepPlanTargetService;


    @GetMapping("list")
    @Operation(summary = "保养计划列表", description = "获取保养计划列表（无分页）", method = "GET")
    public Result<List<EquipmentUpkeepPlan>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<EquipmentUpkeepPlan> list = equipmentUpkeepPlanService.list(EquipmentUpkeepPlan.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "保养计划列表", description = "获取保养计划列表（分页）", method = "GET")
    public Result<Page<EquipmentUpkeepPlan>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentUpkeepPlan> pageResult = equipmentUpkeepPlanService.listPage(EquipmentUpkeepPlan.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("list/{id}")
    @Operation(summary = "根据ID获取保养计划列表", description = "根据ID获取保养计划列表", method = "GET")
    public Result<EquipmentUpkeepPlan> getById(@PathVariable(name = "id", required = true) String id) {
        EquipmentUpkeepPlan equipmentUpkeepPlan = equipmentUpkeepPlanService.getById(EquipmentUpkeepPlan.class, id);
        return Result.OK(equipmentUpkeepPlan);
    }

    @RequestMapping("add")
    @Operation(summary = "保存保养计划", description = "保存保养计划")
    public Result<EquipmentUpkeepPlan> add(@RequestBody EquipmentUpkeepPlan equipmentUpkeepPlan) {
        if(StringUtils.isBlank(equipmentUpkeepPlan.getCode())) {
            SnRuleService snRuleService = SpringUtil.getBean(SnRuleService.class);
            String expression = "UKP";
            String yearmonth = DateUtils.formatDate(new Date(), "yyyyMM");
            String bizNo = (String) snRuleService.execute(expression+yearmonth+"####", null);
            equipmentUpkeepPlan.setCode(bizNo);//
        }

        equipmentUpkeepPlan.setLastPlanStart(equipmentUpkeepPlan.getStartTime());//设置默认值
        equipmentUpkeepPlan.setIsEnable(Integer.parseInt(CommonEnums.YesNo.NO.getCode()));//默认未开启
        equipmentUpkeepPlan.setExecStatus(EquipmentEnums.PlanExecStatus.UNEXEC.getCode());//默认未执行
        equipmentUpkeepPlanService.save(equipmentUpkeepPlan);
        return Result.OK(equipmentUpkeepPlan);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑保养计划", description = "编辑保养计划", method = "PUT")
    public Result<EquipmentUpkeepPlan> edit(@RequestBody EquipmentUpkeepPlan equipmentUpkeepPlan) {
        equipmentUpkeepPlanService.update(equipmentUpkeepPlan);
        return Result.OK(equipmentUpkeepPlan);
    }
    @GetMapping("enable/{id}")
    @Operation(summary = "根据ID启用保养计划", description = "根据ID启用保养计划", method = "GET")
    public Result<EquipmentUpkeepPlan> enable(@PathVariable(name = "id", required = true) String id) {
        EquipmentUpkeepPlan byId = equipmentUpkeepPlanService.getById(EquipmentUpkeepPlan.class, id);
        if (StringUtils.equals(byId.getIsEnable().toString(),CommonEnums.YesNo.YES.getCode())){
            return Result.error("计划已经是已生效状态！");
        }
        if (StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.FINISH.getCode())){
            return Result.error("已完成计划不允许重复启用！");
        }
        if (StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.SCRAP.getCode())){
            return Result.error("已作废计划不允许重复启用！");
        }
        Criteria criteria = Criteria.create();
        criteria.addCriterion("planId", Operator.EQ,byId.getId());
        List<EquipmentUpkeepPlanTarget> targetList = equipmentUpkeepPlanTargetService.list(EquipmentUpkeepPlanTarget.class, criteria);
        if (targetList.isEmpty()){
            return Result.error("保养目标为空，请添加数据！");
        }else{
            for (EquipmentUpkeepPlanTarget target:targetList){
                if (target.getLastUpkeepDate()==null){
                    return Result.error("保养目标"+target.getTargetId()+"_"+target.getTargetName()+"上次保养日期为空，请维护数据！");
                }
            }
        }
        byId.setIsEnable(Integer.parseInt(CommonEnums.YesNo.YES.getCode()));
        equipmentUpkeepPlanService.update(byId);
        return Result.OK(byId);
    }

    @GetMapping("enableAll/{ids}")
    @Operation(summary = "根据ID-批量启用保养计划", description = "根据ID-批量启用保养计划", method = "GET")
    public Result<List<EquipmentUpkeepPlan>> enables(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        List<EquipmentUpkeepPlan> updatedPlans = new ArrayList<>(); // 用来收集所有被启用的计划
        for (String key : id){
            EquipmentUpkeepPlan byId = equipmentUpkeepPlanService.getById(EquipmentUpkeepPlan.class, key);
            if (StringUtils.equals(byId.getIsEnable().toString(),CommonEnums.YesNo.YES.getCode())){
                return Result.error("计划已经是已生效状态！");
            }
            if (StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.FINISH.getCode())){
                return Result.error("已完成计划不允许重复启用！");
            }
            if (StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.SCRAP.getCode())){
                return Result.error("已作废计划不允许重复启用！");
            }
            Criteria criteria = Criteria.create();
            criteria.addCriterion("planId", Operator.EQ,byId.getId());
            List<EquipmentUpkeepPlanTarget> targetList = equipmentUpkeepPlanTargetService.list(EquipmentUpkeepPlanTarget.class, criteria);
            if (targetList.isEmpty()){
                return Result.error("保养目标为空，请添加数据！");
            }else{
                for (EquipmentUpkeepPlanTarget target:targetList){
                    if (target.getLastUpkeepDate()==null){
                        return Result.error("保养目标"+target.getTargetId()+"_"+target.getTargetName()+"上次保养日期为空，请维护数据！");
                    }
                }
            }
            byId.setIsEnable(Integer.parseInt(CommonEnums.YesNo.YES.getCode()));
            equipmentUpkeepPlanService.update(byId);
            updatedPlans.add(byId); // 收集启用的计划
        }
        // 如果至少有一个计划被启用，则返回成功结果；否则返回没有计划被更新的结果
        if (updatedPlans.isEmpty()) {
            return Result.error("没有符合条件的计划被启用！");
        } else {
            // 你可以根据需要返回单个计划或所有启用的计划列表
            // 这里我返回了所有启用的计划列表
            return Result.OK(updatedPlans);
        }
    }
    @GetMapping("disable/{id}")
    @Operation(summary = "根据ID关闭/禁用保养计划", description = "根据ID关闭/禁用保养计划", method = "GET")
    public Result<EquipmentUpkeepPlan> disable(@PathVariable(name = "id", required = true) String id) {
        EquipmentUpkeepPlan byId = equipmentUpkeepPlanService.getById(EquipmentUpkeepPlan.class, id);
        if (StringUtils.equals(byId.getIsEnable().toString(),CommonEnums.YesNo.NO.getCode())){
            return Result.error("计划已经是禁用状态！");
        }
        if (!(StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.UNEXEC.getCode())
                ||StringUtils.equals(byId.getExecStatus(),EquipmentEnums.PlanExecStatus.EXECING.getCode()))){
            return Result.error("仅未执行或者执行中状态的计划可以禁用！");
        }
        byId.setIsEnable(Integer.parseInt(CommonEnums.YesNo.NO.getCode()));
        equipmentUpkeepPlanService.update(byId);
        return Result.OK(byId);
    }
    @DeleteMapping("remove/{ids}")
    @Operation(summary = "根据id删除保养计划", description = "删除保养计划,多个id用英文逗号分隔", method = "DELETE")
    public Result<EquipmentUpkeepPlan> remove(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        for(String key : id){
            equipmentUpkeepPlanService.delete(EquipmentUpkeepPlan.class, key, new SmartCrudPolicyAdapter() {
                @Override
                public boolean beforeDelete(CrudContext context) {
                    Object o = context.getEntity();
                    if (o instanceof EquipmentUpkeepPlan){
                        try {
                            JpaUtil.lind(EquipmentUpkeepPlanTarget.class).equal("planId", ((EquipmentUpkeepPlan) o).getId()).delete();
                            JpaUtil.lind(EquipmentUpkeepPlanDetail.class).equal("planId", ((EquipmentUpkeepPlan) o).getId()).delete();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        }
        return Result.OK();
    }

    @GetMapping("copy/{id}")
    @Operation(summary = "根据id复制保养计划及明细", description = "根据id复制保养计划及明细", method = "GET")
    public Result<EquipmentUpkeepPlan> copy(@PathVariable(name = "id", required = true) String id){
        return equipmentUpkeepPlanService.copy(id);
    }
}
